<?php
/**
 * 默认控制器
 */
class Controller_api extends Controller_Abstract
{
	
	private $appConfig = array('1000'=>'6ddc2b3bb5443f7510ffce31cea5cb1f');
	private $regKeyConfig = array('a88aa9eacb67a03eb63fa7e867ea57b8'=>4);
	private $appErrCode = array(
				'0'=>'操作成功',
				'1001'=>'未提交加密串',
				'1002'=>'请求超时',
				'1003'=>'请求加密错误',
				'1004'=>'需要APPID参数',
				'1005'=>'请求参数不完整',
				'1006'=>'',
			
			
			
				'2001'=>'用户未找到',
				'2002'=>'密码不正确',
				'2003'=>'主叫号码已经认证',
				'2004'=>'主叫号码认证每日限制请求3次',
				'2005'=>'新密码格式不正确,只能纯数字',
				'2006'=>'被叫号码不正确',
				'2007'=>'回拨队列存在,请稍后再试',
				'2008'=>'每日只能获取密码请求3次',
				'2009'=>'代理未打开短信开关',
				'2010'=>'验证码模式错误',
				'2011'=>'用户已存在',
				'2012'=>'未找到快速注册代理',
				'2013'=>'代理未打开手机快速注册',
				'2014'=>'代理余额不足',
				'2015'=>'代理被锁定',
				'2016'=>'验证码请求频率过快,60秒内只能请求1次',
				'2017'=>'验证码错误',
				'2018'=>'请先获取验证码',
				'2019'=>'代理不存在',
				'2020'=>'通讯录格式不正确',
				'2021'=>'礼物接收者不存在',
				'2022'=>'您的余额不足',
				'2023'=>'此礼物需要VIP1才能购买',
				'2024'=>'此礼物需要VIP2才能购买',
				'2025'=>'礼包不存在',
				'2025'=>'抽奖配置不存在',
				'2026'=>'需要是VIP1才能抽取',
				'2027'=>'超过每日限制的抽奖次数',
				'2028'=>'奖池已经被抽完啦',
				'2029'=>'很遗憾,什么也没有抽中,谢谢您的参与',
				'2030'=>'充值卡密码错误',
				'2031'=>'充值卡已经使用',
				'2032'=>'充值卡过期',
				'2033'=>'充值卡金额为0',
				'2034'=>'充值卡所属代理余额不足',
				'2035'=>'充值卡所属代理被锁定'
			);
	private $requestData = array();
	/**
	 * 记录API请求日志
	 * @param string $mgs
	 */
	private function logs($msg)
	{
		$action_log = trim($this->_context->action_name);
		Helper_Common::log($msg,$action_log);
	}
	/**
	 * 输出消息
	 * @param int $code 错误码
	 * @param string $msg 错误信息
	 * @param array $data 输出数据
	 */
	private function responseMsg($code,$data = array())
	{
		$msg = isset($this->appErrCode[$code]) ? trim($this->appErrCode[$code]) : '系统错误';
		$result = array('errcode' => intval($code),'errmsg'=>trim($msg),'data'=>$data);
		$this->logs("RESPONSE:".print_r($result,true));
		echo json_encode($result);
		exit();
	}
	/**
	 * 请求参数效验
	 * @param array $questData 当次请求需要效验的参数键 
	 */
	private function checkParamValid($questData)
	{
		if(!isset($questData['sign']) || !$questData['sign'])
		{
			return 1001;//未提交sign
		}else {
			$sign = strtolower(trim($questData['sign']));
			unset($questData['sign']);
			$time = time();
			if(!isset($questData['timeline']) || abs(intval($questData['timeline']) - $time) > 86400*30 )
			{
				return 1002;//timeline超市
			}else if(!isset($questData['appid']) || !$questData['appid'] || !isset($this->appConfig[$questData['appid']]))
			{
				return 1004;//need appid	
			}else
			{
				$appkey = trim($this->appConfig[$questData['appid']]);
				ksort($questData,SORT_STRING);
				$makeSign = implode('', $questData).$appkey;
				$this->logs("make string : {$makeSign},md5=".md5($makeSign));
				$makeSign = md5($makeSign);
				if ($makeSign == $sign)
				{
					return 0;
				}else{
					return 1003;//sign 不等于
				}
			}
		} 
	}
	/**
	 * 检测参数是否齐全
	 * @param array $needParam
	 */
	private function checkNeedParam($needParam)
	{
		$this->logs("REQUEST ".$this->_context->action_name." :".print_r($_REQUEST,true));
		foreach ($needParam as $v)
		{
			if(!isset($_REQUEST[$v]))
			{
				$this->logs('need param:'.$v);
				$this->responseMsg(1005);
			}else{
				$this->requestData[$v] = $_REQUEST[$v];
			}
		}
		return true;
	}
	/**
	 * 用户信息刷新
	 */
	public function actionUserLogin()
	{
		$needParam = array('appid','username','password','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,balance,password,expireddate,point,agent_id,bind_ipphone')->getOne();
		if(!$user->id())
		{
			$this->responseMsg(2001);//未找到用户
		}else if($user->password !== $this->requestData['password']){
			$this->responseMsg(2002);//密码不正确
		}else{
			$userInfo = array(
						'balance'=>sprintf("%.4f",$user->balance),
						'expdate'=>$user->expireddate,
						'point'=>$user->point,
						'vip1'=>$user->vip1->id() ? 1 : 0,
						'vip2'=>$user->vip2->id() ? 1 : 0,
						'platform'=>$user->agent_id,
						'authMobile'=> !$user->bind_ipphone ? 0 : trim($user->bind_ipphone)
					);
			$this->responseMsg(0,$userInfo);
		}
	}
	/**
	 * 找回密码
	 */
	public function actionFindPwd()
	{
		$needParam = array('appid','username','mode','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,acctname,password,agent_id')->getOne();
		if($user->id())
		{
			$isDisbale = Findpwdlog::find('userid = ? and date = ?',$user->id,date('Y-m-d'))->getCount('userid');
			if($isDisbale>=3)
			{
				$this->responseMsg(2008);
			}else{
				$isDisbale = new Findpwdlog();
				$isDisbale->userid = $user->id;
				$isDisbale->date = date('Y-m-d');
				$isDisbale->ip = Helper_Common::get_ip();
				$isDisbale->save(0,'create');
			}
			
				if (intval($this->requestData['mode']) == 1)
				{
					$sql = "INSERT INTO fscall.outcall_cc(acct,caller,oparg,type) VALUES('{$user->acctname}','{$user->acctname}','{$user->password}',0)";
					QDB::getConn('fscall')->execute($sql);
					$this->responseMsg(0);
				}else{
					//sms
					if($user->agent->smsurl  && $user->agent->smsflag)
					{
						$msg = "({$user->acctname})您当前的密码为:{$user->password},请妥善保管,每日只能使用此功能3次.";
						//$msg = $acctuser->acctname.",您此次清除用户数据的操作验证码为:".$rnd.",请尽快使用.";
						$msglength = mb_strlen($msg,'UTF-8');
						$msg = urlencode($msg);
						$url = str_replace('%m%', $user->acctname, $user->agent->smsurl);
						$url = str_replace('%s%', $msg, $url);
						$result = Helper_Common::cget($url);
						QLog::log('smssend:'.$url.'|'.$result);
						$result = iconv("GB2312","UTF-8",$result);
						QDB::getConn()->execute("call smscost({$user->agent->id},0.01)");
						$this->responseMsg(0);
					}else{
						$this->responseMsg(2009);
					}
				}
		}else{
			$this->responseMsg(2001);
		}
	}
	/**
	 * 充值卡充值
	 */
	public function actionPayMent()
	{
		$needParam = array('appid','username','cardname','cardpass','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		
		$mzcard = mzcard::find('id = ? and cardpass = ? ',trim($this->requestData['cardname']),$this->requestData['cardpass'])->getOne();
		if($mzcard->id())
		{
			if($mzcard->used == 1)
			{
				$this->responseMsg(2031);//充值卡已经被使用
			}else if(strtotime($mzcard->expdate) < time())
			{
				$this->responseMsg(2032);//充值卡已经过期
			}else if($mzcard->balance <= 0)
			{
				$this->responseMsg(2033);//余额为0	
			}else{
				try {
					$status = QDB::getConn('appmz')->execute("SELECT flag from (SELECT app_mz.acct_check_balance({$mzcard->agent_id},{$mzcard->balance}) as flag)A")->fetchOne();
					
				} catch (Exception $e) {
					$status = 0;
				}
				QDB::getConn('appmz')->close();
				QDB::getConn('appmz')->connect();
				if( intval($status) == 1 )
				{
					$mzacct = mzacct::find('id = ?',$mzcard->agent_id)->getOne();
					if( $mzacct->id() && $mzacct->status == 1)
					{
						$this->responseMsg(2035);//充值卡所属代理被锁定
					}else{
						$user = Acctuser::find('acctname = ?',$this->requestData['username'])->getOne();
						if($user->id())
						{
							//已经存在
							$payBlance = abs($mzcard->balance);
							$user->balance += $payBlance;
							$user->expireddate  = date('Y-m-d',strtotime("+90 day",strtotime($user->expireddate )));
							if($user->changeagent == 1)//免费注册的
							{
								$user->agent_id = 4;
								$user->gatewaygroupid = 4;
								$user->gatewaygroupid_acall = 5;
								$user->mz_agentid = $mzcard->agent_id;
								$user->save(0,'update');
								//
							}
							$user->save(0,'update');
						}else{
							//新开
								
							$user = new self();
							$user ->agent_id = 4;
							$user ->admin_id = 1;
							$user->vouchercard = $mzcard->id;
							$user ->acctname = Helper_Common::trim($this->requestData['username']);
							$user ->password = $mzcard->cardpass;
							$user ->balance = $mzcard->balance;
							//$acctuser->bindexten_type = 0;
							//$user ->expireddays = $card->expireddays;
							$user ->rategroupid = 4;
							$user ->rategroupid_acall = 5;
							//$user ->limitbalance = $card->limitbalance;
							$user->expireddate = date('Y-m-d',strtotime("+1 yeah",time()));
							$user->save(0,'create');
						}
						//add log
						$dataInfo = array(
								'modetype'=>0,
								'username'=>$user->acctname,
								'cardname'=>$mzcard->id,
								'cardpass'=>$mzcard->cardpass,
								'balance'=>$mzcard->balance,
								'agent_id'=>$mzcard->agent_id,
								'created'=>time(),
								'ip'=>Helper_Common::get_ip(),
								'modetype'=>$mzcard->modetype
								);
						$mzcardlog = new mzcardlog($dataInfo);
						$mzcardlog->save(0,'create');
						$mzcard->username = $user->acctname;
						$mzcard->use_time = date('Y-m-d H:i:s');
						$mzcard->used = 1;
						
						$mzcard->save(0,'update');
						//更新面值
						QDB::getConn('appmz')->execute("CALL app_mz.acct_usercard_cost({$mzacct->id},{$mzcard->balance})");
						QDB::getConn('appmz')->close();
						$data = array('balance'=>$user->balance,'expdate'=>$user->expireddate,'cardbalance'=>$mzcard->balance);
						$this->responseMsg(0,$data);
						
					}
				}else{
					$this->responseMsg(2034);//充值卡所属代理余额不足
				}
			}
		}else{
			$this->responseMsg(2030);//充值卡卡密错误
		}
		
		
	}
	/**
	 * 主叫认证
	 */
	public function actionAuthMobile()
	{
		$needParam = array('appid','username','password','mode','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,acctname,password,bind_ipphone')->getOne();
		if(!$user->id())
		{
			$this->responseMsg(2001);
		}else if($user->password !==$this->requestData['password'])
		{
			$this->responseMsg(2002);	
		}else if(!$user->bind_ipphone){
			$this->responseMsg(2003);
		}else{
			$authNum = Acctuser::insertAuth($user->acctname);
			if($authNum <= 2)
			{
				$this->responseMsg(0);
			}else{
				$this->responseMsg(2004);
			}
		}
	}
	/**
	 * 修改密码
	 */
	public function actionChangePwd()
	{
		$needParam = array('appid','username','password','newpassword','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		if(!QValidator::validate_is_digits($this->requestData['newpassword']))
		{
			$this->responseMsg(2005);//新密码格式不正确
		}else{
			$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,acctname,password')->getOne();
			if(!$user->id())
			{
				$this->responseMsg(2001);
			}else if($user->password !== $this->requestData['password']){
				$this->responseMsg(2002);
			}else{
				$user->password = $this->requestData['newpassword'];
				$user->save(0,'update');
				$this->responseMsg(0);
			}			
		}
	}
	/**
	 * 回拨
	 */
	public function actionCallBack()
	{
		$needParam = array('appid','username','password','callnum','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		if(!Helper_Param::_phone($this->requestData['callnum']))
		{
			$this->responseMsg(2006);//被叫号码格式不正确
		}else{
			$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,acctname,password')->getOne();
			if(!$user->id())
			{
				$this->responseMsg(2001);
			}else if($user->password !== $this->requestData['password']){
				$this->responseMsg(2002);
			}else{
				$isone = Cbsubmit::find('bindname = ? and destination_number = ?',$user->acctname,$this->requestData['callnum'])->getCount('id');
				if($isone){
					$this->responseMsg(2007);//存在此呼叫队列 请勿重复提交
				}else{
					Cbsubmit::call($user->acctname, $this->requestData['callnum']);
					$this->responseMsg(0);
				}
			}
		}
	}
	/**
	 * 获取注册验证码
	 */
	public function actionGetRegCode()
	{
		$needParam = array('appid','username','password','regkey','mode','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		//regkey = a88aa9eacb67a03eb63fa7e867ea57b8
		if(!in_array(intval($this->requestData['mode']), array(0,1)))
		{
			$this->responseMsg(2010);
		}else{
			$user = Acctuser::find('acctname = ?',$this->requestData['username'])->getCount('id');
			if($user)
			{
				$this->responseMsg(2011);//用户存在
			}else{
				$acct = Acct::find('wapquickkey = ?',$this->requestData['regkey'])->setColumns('id,wapquickopen,balance,overbalance,enable,smsurl')->getOne();
				
				if(!$acct->id())
				{
					$this->responseMsg(2012);//未找到快速注册代理
				}else if($acct->wapquickopen == 0){
					$this->responseMsg(2013);//代理未打开手机快速注册
				}else if(($acct->balance + $acct->overbalance) <= 0)
				{
					$this->responseMsg(2014);//代理余额不足
				}else if($acct->enable <> 1)
				{
					$this->responseMsg(2015);//代理被锁定
				}else{
					$username = Helper_Common::trim($this->requestData['username']);
					$count = Wapquickreg::find('acctname = ? and created >= ?',$username,time()-60)->getCount('id');
					if($count)
					{
						$this->responseMsg(2016);//60秒内只能请求1次						
					}else{
						$code = Helper_Common::get_rnd(0, 6);
						$Log = new Wapquickreg();
						$Log->acctkey = $this->requestData['regkey'];
						$Log->code = $code;
						$Log->acctname = $username;
						$Log->pwd = trim($this->requestData['password']);
						$Log->status =0;
						$Log->save(0,'create');
					}
					if($this->requestData['mode'] == 0)
					{
						//TODOO 语音验证码
					}else{
						$smsurl = $acct->smsurl ;
						$smsurl = str_replace('%m%', $username, $smsurl);
						$smsurl = str_replace('%s%', "您的快捷注册验证码为:{$code}", $smsurl);
						$smsresult = Helper_Common::cget($smsurl);
						Helper_Common::log("interface/quickreg url:{$smsurl},result:{$smsresult}",'quickreg');
					}
					$this->responseMsg(0);
				}
			}
		}
	}
	public function actionQuickReg()
	{
		$needParam = array('appid','username','regkey','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		if(1){
			$user = Acctuser::find('acctname = ?',$this->requestData['username'])->getCount('id');
			if($user)
			{
				$this->responseMsg(2011);//用户存在
			}else{
				$acct = Acct::find('wapquickkey = ?',$this->requestData['regkey'])->setColumns('id,wapquickopen,balance,overbalance,enable,smsurl')->getOne();
		
				if(!$acct->id())
				{
					$this->responseMsg(2012);//未找到快速注册代理
				}else if($acct->wapquickopen == 0){
					$this->responseMsg(2013);//代理未打开手机快速注册
				}else if(($acct->balance + $acct->overbalance) <= 0)
				{
					$this->responseMsg(2014);//代理余额不足
				}else if($acct->enable <> 1)
				{
					$this->responseMsg(2015);//代理被锁定
				}else{
					$username = Helper_Common::trim($this->requestData['username']);
					$count = Wapquickreg::find('acctname = ? and created >= ?',$username,time()-60)->getCount('id');
					if($count)
					{
						$this->responseMsg(2016);//60秒内只能请求1次
					}else{
						$code = Helper_Common::get_rnd(0, 6);
						$Log = new Wapquickreg();
						$Log->acctkey = $this->requestData['regkey'];
						$Log->code = $code;
						$Log->acctname = $username;
						$Log->pwd = Helper_Common::get_rnd(0, 4);
						$Log->status =0;
						$Log->save(0,'create');
					}
					$acct = Acct::find('wapquickkey = ? and wapquickopen = 1',$Log->acctkey)->getOne();
					if (!$acct->id())
					{
						$this->responseMsg(2019);//代理已经不存在
					}
					$acctwap = Acctwapset::find('acctid = ? ',$acct->id)->getOne();
					$acctuser = new Acctuser();
					$acctuser->agent_id = $acct->id;
					$acctuser->admin_id = $acct->admin_id;
					$acctuser->unionacctname = '';
					$acctuser->acctname = $this->requestData['username'];
					$acctuser->password = $Log->pwd;
					$acctuser->balance = $acctwap->safe_money;
					$acctuser->activedate = date('Y-m-d');
					$acctuser->expireddays = $acctwap->expireddays;
					$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->activedate} + {$acctuser->expireddays} day"));
					//$acctuser->bindexten_type = 0;
					//$acctuser->expireddays = $card->expireddays;
					$acctuser->changeagent = 1;
					$acctuser->rategroupid = $acctwap->rategroupid;
					$acctuser->rategroupid_acall = $acctwap->rategroupid_acall;
					$acctuser->limitbalance = 0;
					$acctuser->bind_ipphone = $this->requestData['username'];
					try {
						$acctuser->save(0,'create');
						Syslog::notloginlogs("{$acct->acctname} 下的 {$this->requestData['username']} 使用手机快速注册");
						$Log->status = 1;
						$Log->save(0);
						//return true;
					} catch (Exception $e) {
					
					}
					$sql = "call fscall.httppost('{$this->requestData['username']}','','',1)";
					QDB::getConn()->execute($sql);
					QDB::getConn()->close();
					$this->responseMsg(0);
				}
			}
		}
	}
	/**
	 * 根据注册验证码注册
	 */
	public function actionRegByCode()
	{
		$needParam = array('appid','username','code','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		if(!$this->requestData['code'])
		{
			$this->responseMsg(2017);//验证码错误
		}else{
			$log = Wapquickreg::find('acctname = ? and status = 0',$this->requestData['username'])->order('created desc')->getOne();
			if(!$log->id())
			{
				$this->responseMsg(2018);//请先获取验证码
			}else{
				if(intval($log->code) === intval($this->requestData['code']))
				{
					$acct = Acct::find('wapquickkey = ? and wapquickopen = 1',$log->acctkey)->getOne();
					if (!$acct->id())
					{
						$this->responseMsg(2019);//代理已经不存在
					}
					$acctwap = Acctwapset::find('acctid = ? ',$acct->id)->getOne();
					$acctuser = new Acctuser();
					$acctuser->agent_id = $acct->id;
					$acctuser->admin_id = $acct->admin_id;
					$acctuser->unionacctname = '';
					$acctuser->acctname = $this->requestData['username'];
					$acctuser->password = $log->pwd;
					$acctuser->balance = $acctwap->safe_money;
					$acctuser->activedate = date('Y-m-d');
					$acctuser->expireddays = $acctwap->expireddays;
					$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->activedate} + {$acctuser->expireddays} day"));
					//$acctuser->bindexten_type = 0;
					//$acctuser->expireddays = $card->expireddays;
					$acctuser->changeagent = 1;
					$acctuser->rategroupid = $acctwap->rategroupid;
					$acctuser->rategroupid_acall = $acctwap->rategroupid_acall;
					$acctuser->limitbalance = 0;
					$acctuser->bind_ipphone = $this->requestData['username'];
					try {
						$acctuser->save(0,'create');
						Syslog::notloginlogs("{$acct->acctname} 下的 {$this->requestData['username']} 使用手机验证码{$this->requestData['code']} 成功注册");
						$log->status = 1;
						$log->save(0);
						//return true;
					} catch (Exception $e) {
		
					}
					$sql = "call fscall.httppost('{$this->requestData['username']}','','',1)";
					QDB::getConn()->execute($sql);
					QDB::getConn()->close();
					$this->responseMsg(0);
				}else{
					$this->responseMsg(2017);
				}
			}
		}
	}
	/**
	 * sip在线监测
	 */
	public function actionSipStatus()
	{
		$needParam = array('appid','username','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id')->getOne();
		if(!$user->id())
		{
			$this->responseMsg(2001);	
		}else{
			$sql = "SELECT status FROM fscall.sip_online WHERE sipuser = '{$this->requestData['username']}' limit 1";
			$status = QDB::getConn('fscall')->execute($sql)->fetchRow();
			if(count($status) == 0)
			{
				$data = array('status'=>0);
			}else{
				$data = array('status'=>intval($status['status']));
			}
			$this->responseMsg(0,$data);
		}
	}
	/**
	 * 发起悄悄话
	 */
	public function actionQuietlyCall()
	{
		$needParam = array('appid','username','password','quietlynum','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		
		//暂时未开通
		$this->responseMsg(0);
		//Todoo
	}
	/**
	 * 抽奖接口
	 */
	public function actionLottery()
	{
		$needParam = array('appid','username','password','lotteryid','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,acctname,password')->getOne();
		if(!$user->id())
		{
			$this->responseMsg(2001);
		}else if($user->password !== $this->requestData['password']){
			$this->responseMsg(2002);
		}else if(!isset($user->vip1->acct_id)){
			$this->responseMsg(2026);//need vip1
		}else{
			$lottery = lotteryitems::find('lottery_id = ?',intval($this->requestData['lotteryid']))->getOne();
			if(!$lottery->id()){
				$this->responseMsg(2025);
			}else{
				$isJoin = lotterylogs::find('lottery_id = ? and user_id = ? and created = ?',$lottery->lottery_id,$user->id,strtotime(date('Y-m-d')))->getCount('id');
				if($isJoin >= $lottery->maxnum)
				{
					$this->responseMsg(2027);//超过每人限制次数
				}else{
					$template = lotterytemplate::find('used = 0')->order('id asc')->getOne();
					if($template->id())
					{
						if( intval($template->point) > 0){
							$user->point += abs(intval($template->point));
							$user->save(0);
							//add log
							$loginfo = array(
									'lottery_id'=>$lottery->lottery_id,
									'user_id'=>$user->id,
									'acctname'=>$user->acctname,
									'status'=>0,
									'point'=>abs(intval($template->point)),
									'created'=>strtotime(date('Y-m-d'))
									);
							$log = new lotterylogs($loginfo);
							$log->save(0,'create');
							$this->responseMsg(0,array('point'=>abs(intval($template->point))));
						}else{
							$this->responseMsg(2029);//很遗憾,什么也没有抽中
						}
					}else{
						$this->responseMsg(2028);//奖品池抽完
					}
				}
				
			}
		}
		
		$this->responseMsg(0);
	}
	/**
	 * 系统信息
	 */
	public function actionInitInfo()
	{
		$needParam = array('appid','username','timeline','sign');
		$this->checkNeedParam($needParam);
		dump($this->requestData);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$u = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,agent_id,mz_agentid')->asArray()->getOne();
		$sipinfo = siphosts::getSip(Helper_Common::get_ip());
		$pubconfig = pubconfig::find("agent_id = 1 and (name = ? or name = ?)",'gonggao1','help')->setColumns('name,value')->asArray()->getAll();
		$pubconfig = Helper_Array::toHashmap($pubconfig, 'name','value');
		$data = array(
				'siphost'=>$sipinfo['siphost'],
				'sipport'=>$sipinfo['sipport'],
				'explain'=>$pubconfig['help'],
				'bulletin1'=>$pubconfig['gonggao1'],
				'bulletin2'=>'',
				'appname'=>''
				);
		if(isset($u['agent_id']))
		{
			//已经注册的用户 查找是否使用面值卡充值
			$sql = "SELECT appname,bulletin as bulletin2 FROM app_mz.mz_acct WHERE id = ".intval($u['mz_agentid']);
		}else{
			//未注册用户 返回管理设置
			$sql = "SELECT appname,bulletin as bulletin2 FROM app_mz.mz_acct WHERE `level` = 0 limit 1";
		}
		$mzinfo = QDB::getConn()->execute($sql)->fetchRow();
		isset($mzinfo['appname']) && $data['appname'] = $mzinfo['appname'];
		isset($mzinfo['bulletin2']) && $data['bulletin2'] = $mzinfo['bulletin2'];
		$this->responseMsg(0,$data);
		
	}
	/**
	 * 信息反馈
	 */
	public function actionFeedBack()
	{
		$needParam = array('appid','username','password','content','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$u = Acctuser::find('acctname = ? and password = ?',$this->requestData['username'],$this->requestData['password'])->setColumns('id')->getOne();
		if(!$u->id())
		{
			$this->responseMsg(2001);
		}else{
			$addlog = new feedback();
			$addlog->acct_id =$u->id;
			$addlog->content = h($this->requestData['content']);
			$addlog->appid = $this->requestData['appid'];
			$addlog->created = time();
			$addlog->save();
			$this->responseMsg(0);
		}
	}
	/**
	 * 加载抽奖配置
	 */
	public function actionloadlottery()
	{
		$needParam = array('appid','username','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$u = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id')->getOne();
		if(!$u->id())
		{
			$this->responseMsg(2001);
		}else{
			$lottery = lotteryitems::find()->setColumns('lottery_id,imgurl,desc')->asArray()->getAll();
			$this->responseMsg(0,$lottery);
		}
	}
	/**
	 * 匹配好友
	 */
	public function actionMatchFriends()
	{
		//张三:18080801234,李四:13512345432
		$needParam = array('appid','username','password','contacts','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,acctname,password')->getOne();
		if(!$user->id())
		{
			$this->responseMsg(2001);
		}else if($user->password !== $this->requestData['password']){
			$this->responseMsg(2002);
		}else if(!strpos($this->requestData['contacts'], ',')){
			$this->responseMsg(2020);
		}else{
			$userNames = array();
			//清空已经存在的数据
			//usermobilecontacts::meta()->deleteWhere('user_id = '.$user->id);
			$contacts = explode(',', $this->requestData['contacts']);
			foreach ($contacts as $item)
			{
				$line = explode(':', $item);
				if(count($line) !== 2)continue;
				$mobile = Helper_Common::trim($line[1]);
				$record = usermobilecontacts::find('user_id = ? and mobile = ?',$user->id,$mobile)->getOne();
				if(!$record->id()){
					$record = new usermobilecontacts();
					$record->user_id = $user->id;
					$record->mobile = $mobile;
					$record->name = h($line[0]);
					$record->save(0);
				}
				$userNames[] = $mobile;
			}
			$data = '';
			if(count($userNames) > 0)
			{
				$haveFriend = Acctuser::find(array('acctname'=>array_values($userNames)))->setColumns('acctname')->asArray()->getAll();
				if(count($haveFriend))
				{
					$haveFriend = Helper_Array::toHashmap($haveFriend, 'acctname','acctname');
					$data = implode(',', $haveFriend);
				}
			}
			$this->responseMsg(0,$data);
		}
	}
	/**
	 * 加载礼品配置
	 */
	public function actionLoadGift()
	{
		$needParam = array('appid','username','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$u = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id')->getOne();
		if(!$u->id())
		{
			$this->responseMsg(2001);
		}else{
			$data = appgifts::find()->setColumns('giftid,name,imgurl,desc,limitlv,price,point,rate')->asArray()->getAll();
			$this->responseMsg(0,$data);
		}
	}
	
	/**
	 * 赠送礼物
	 */
	public function actionHandselGift()
	{
		$needParam = array('appid','username','password','receiveuser','giftid','number','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$user = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id,acctname,password,balance,point')->getOne();
		if(!$user->id())
		{
			$this->responseMsg(2001);
		}else if($user->password !== $this->requestData['password']){
			$this->responseMsg(2002);
		}else if( floatval($user->balance) < 0 || intval($user->point) < 0)
		{
			$this->responseMsg(2022);//您的余额不足	
		}else{
			$receiveUser = Acctuser::find('acctname = ?',Helper_Common::trim($this->requestData['receiveuser']))->getOne();
			if(!$receiveUser->id())
			{
				$this->responseMsg(2021);//接收者不存在
			}else{
				$num = abs(intval($this->requestData['number']));
				$gift = appgifts::find('giftid = ?',intval($this->requestData['giftid']))->getOne();
				if(!$gift->id())
				{
					$this->responseMsg(2025);
				}else if($gift->limitlv == 2 && !isset($user->vip1->acct_id))
				{
					$this->responseMsg(2023);//等级不够需要VIP1
				}else if($gift->limitlv == 3 && !isset($user->vip2->acct_id))
				{
					$this->responseMsg(2024);//需要等级VIP2
				}else if($user->balance < $gift->price*$num || $user->point < $gift->point*$num)
				{
					$this->responseMsg(2022);
				}else{
					$rate_money = $gift->price * ($gift->rate / 100) * $num;
					$rate_point = $gift->point * ($gift->rate / 100) * $num;
					if($gift->price)$user->balance = $user->balance - $gift->price * $num;
					if($gift->point)$user->point = $user->point - $gift->point * $num;
					if($gift->price || $gift->point)
					{
						//
						$user->save(0);
						$receiveUser->balance += ($gift->price * $num - $rate_money);
						$receiveUser->point += ($gift->point * $num - $rate_point);
						$receiveUser->save(0);
						//add log
						$loginfo = array(
								'send_username'=>$user->acctname,
								'send_uid'=>$user->id,
								'receive_username'=>$receiveUser->acctname,
								'receive_uid'=>$receiveUser->id,
								'giftid'=>$gift->giftid,
								'number'=>$num,
								'point'=>$gift->point,
								'price'=>$gift->price,
								'rate'=>$gift->rate,
								'created'=>time()
								);
						$log = new appgiftlogs($loginfo);
						$log->save(0,'create');
					}
					$this->responseMsg(0);
				}
			}
		}
			
	}
	/**
	 * 礼物接收记录
	 */
	public function actionGiftReceiveLog()
	{
		$needParam = array('appid','username','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$u = Acctuser::find('acctname = ?',$this->requestData['username'])->setColumns('id')->getOne();
		if(!$u->id())
		{
			$this->responseMsg(2001);
		}else{
			$lastLog = appgiftlogs::find('receive_uid = ?',$u->id)->order('created desc')->limit(0,5)->getAll();
			$data = array();
			foreach ($lastLog as $item)
			{
				$data[] = array(
						'giftid'=>$item->giftid,
						'name'=>$item->gift->name,
						'desc'=>$item->gift->desc,
						'number'=>$item->number,
						'fromuser'=>$item->send_username,
						'senddate'=>date('Y-m-d H:i:s',$item->created)
						);
			}
			$this->responseMsg(0,$data);
		}
	}
	/**
	 * 商户申请
	 */
	public function actionapplyagent()
	{
		$needParam = array('appid','name','address','phone','contact','timeline','sign');
		$this->checkNeedParam($needParam);
		$signCheck = $this->checkParamValid($this->requestData);
		if($signCheck !== 0)$this->responseMsg($signCheck);
		$data = array(
				'name'=>h(trim($this->requestData['name'])),
				'address'=>h(trim($this->requestData['address'])),
				'phone'=>h(trim($this->requestData['phone'])),
				'contact'=>h(trim($this->requestData['contact']))
				);
		$log = new mzapplyagent($data);
		$log->save(0,'create');
		$this->responseMsg(0);
	}
}


